import { Byte } from '../../api/io/Byte';
import { HashMap } from '../../api/struct/HashMap';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';
import { MathUtils } from '../../api/math/MathUtils';



/**天赋属性枚举*/
export const enum E_Talent {
	/**每日重置次数*/
	RESET_TIMES = 0,
	/**上次重置次数清零时间*/
	LAST_CLEAR_RESET_TIME = 1,
	/**已使用的天赋点*/
	USE_POINT_COUNT = 2,
	/**天赋等级*/
	TALENT_LEVEL = 3,
	/**枚举数量*/
	EnumCount = 4
}


/**天赋*/
export class Talent {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_TALENT_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_TALENT_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: Talent[] = [];

	/**创建入口*/
	public static create(json?: string): Talent {
		const c = this.POOL.pop() || new Talent();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**每日重置次数 (uint16)*/
	protected _resetTimes: number;
	/**上次重置次数清零时间 (long)*/
	protected _lastClearResetTime: number;
	/**已使用的天赋点 (uint16)*/
	protected _usePointCount: number;
	/**天赋等级 (uint32, uint16)*/
	protected _talentLevel: HashMap<number, number> = null;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (Talent.POOL.indexOf(this) === -1) {
			Talent.POOL.push(this);
		}
	}

	/**每日重置次数*/
	public get resetTimes() {
		return this._resetTimes;
	}


	/**每日重置次数*/
	public set resetTimes(v: number) {
		this._resetTimes = v;
	}


	/**上次重置次数清零时间*/
	public get lastClearResetTime() {
		return this._lastClearResetTime;
	}


	/**上次重置次数清零时间*/
	public set lastClearResetTime(v: number) {
		this._lastClearResetTime = v;
	}


	/**已使用的天赋点*/
	public get usePointCount() {
		return this._usePointCount;
	}


	/**已使用的天赋点*/
	public set usePointCount(v: number) {
		this._usePointCount = v;
	}


	/**设置天赋等级*/
	public putTalentLevel(k: number, v: number): number {
		const ov = this._talentLevel.put(k, v);
		return ov || 0;
	}


	/**获取天赋等级*/
	public getTalentLevel(k: number) {
		return this._talentLevel.get(k) || 0;
	}


	/**删除天赋等级*/
	public removeTalentLevel(k: number): number {
		const ov = this._talentLevel.remove(k);
		return ov || 0;
	}


	/**获取天赋等级映射表-键值(外部改变将导致出错，只能用于遍历)*/
	public getTalentLevelKeys(): number[] {
		return this._talentLevel.getKeys();
	}


	/**获取天赋等级映射表-值(外部改变将导致出错，只能用于遍历)*/
	public getTalentLevelValues(): number[] {
		return this._talentLevel.getValues();
	}


	/**清空天赋等级映射表*/
	public clearTalentLevelMap(): void {
		this._talentLevel.clear();
	}



	/**通过枚举获取值*/
	public getV(k: E_Talent): any {
		switch (k) {
			case E_Talent.RESET_TIMES: return this._resetTimes;
			case E_Talent.LAST_CLEAR_RESET_TIME: return this._lastClearResetTime;
			case E_Talent.USE_POINT_COUNT: return this._usePointCount;
			case E_Talent.TALENT_LEVEL: return this._talentLevel;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_Talent, v: any): void {
		switch (k) {
			case E_Talent.RESET_TIMES: this._resetTimes = v; break;
			case E_Talent.LAST_CLEAR_RESET_TIME: this._lastClearResetTime = v; break;
			case E_Talent.USE_POINT_COUNT: this._usePointCount = v; break;
			case E_Talent.TALENT_LEVEL: this._talentLevel = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//每日重置次数
		this._resetTimes = 0;
		//上次重置次数清零时间
		this._lastClearResetTime = 0;
		//已使用的天赋点
		this._usePointCount = 0;
		//天赋等级
		if (this._talentLevel) {
			this._talentLevel.clear();
		}
		else {
			this._talentLevel = new HashMap<number, number>();
		}
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._resetTimes) {
			json.resetTimes = this._resetTimes;
		}
		if (this._lastClearResetTime) {
			json.lastClearResetTime = this._lastClearResetTime;
		}
		if (this._usePointCount) {
			json.usePointCount = this._usePointCount;
		}
		if (this._talentLevel.size() > 0) {
			const ks = this._talentLevel.getKeys();
			const vs = this._talentLevel.getValues();
			json.talentLevel = [ks, vs];
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.resetTimes) {
			this._resetTimes = json.resetTimes;
		}
		if (json.lastClearResetTime) {
			this._lastClearResetTime = json.lastClearResetTime;
		}
		if (json.usePointCount) {
			this._usePointCount = json.usePointCount;
		}
		if (json.talentLevel) {
			const ks: number[] = json.talentLevel[0];
			const vs: number[] = json.talentLevel[1];
			if (ks && vs && ks.length === vs.length) {	//json
				this._talentLevel.setKeyAndValueList(ks, vs);
			}
			else if (json.talentLevel.getKeys && json.talentLevel.getValues) {	//结构体
				const ks2 = json.talentLevel.getKeys();
				const vs2 = json.talentLevel.getValues();
				if (ks2 && vs2 && ks2.length === vs2.length) {
					for (let i = 0, len = vs2.length; i < len; i++) {
						this._talentLevel.put(ks2[i], vs2[i]);	//重新添加，防止数据公用后被释放导致bug
					}
				}
			}
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeUint16(this._resetTimes);
		byte.writeLongNumber(this._lastClearResetTime);
		byte.writeUint16(this._usePointCount);
		//天赋等级
		{
			const ks = this._talentLevel.getKeys();
			const vs = this._talentLevel.getValues();
			const len = ks.length;
			byte.writeUint16(len);
			for (let i = 0; i < len; i++) {
				byte.writeUint32(ks[i]);
				byte.writeUint16(vs[i]);
			}
		}
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._resetTimes = byte.readUint16();
		this._lastClearResetTime = byte.readLongNumber();
		this._usePointCount = byte.readUint16();
		//天赋等级
		{
			const len = byte.readUint16();
			for (let i = 0; i < len; i++) {
				const k = byte.readUint32();
				const v = byte.readUint16();
				this._talentLevel.put(k, v);
			}
		}
		return this;
	}


	/**克隆*/
	public clone(): Talent {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = Talent.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = Talent.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//每日重置次数
			if (idx === E_Talent.RESET_TIMES) {
				const oldv = this._resetTimes;
				this._resetTimes = us[i + 1];
				IAsync.dispatch(eventID, idx, this._resetTimes, oldv);
				i += 2;
				continue;
			}
			//上次重置次数清零时间
			if (idx === E_Talent.LAST_CLEAR_RESET_TIME) {
				const oldv = this._lastClearResetTime;
				this._lastClearResetTime = us[i + 1];
				IAsync.dispatch(eventID, idx, this._lastClearResetTime, oldv);
				i += 2;
				continue;
			}
			//已使用的天赋点
			if (idx === E_Talent.USE_POINT_COUNT) {
				const oldv = this._usePointCount;
				this._usePointCount = us[i + 1];
				IAsync.dispatch(eventID, idx, this._usePointCount, oldv);
				i += 2;
				continue;
			}

			//天赋等级
			if (idx === E_Talent.TALENT_LEVEL) {
				const k: number = us[i + 1];
				const newv :number = us[i + 2];
				const oldv = this.putTalentLevel(k, newv);
				IAsync.dispatch(eventID, idx, k, newv, oldv);
				i += 3;
				continue;
			}

			console.error('[Struct Data] can not find enum in Talent with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: Talent): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._resetTimes !== other._resetTimes) {
			updates.push(E_Talent.RESET_TIMES, this._resetTimes);
		}
		if (this._lastClearResetTime !== other._lastClearResetTime) {
			updates.push(E_Talent.LAST_CLEAR_RESET_TIME, this._lastClearResetTime);
		}
		if (this._usePointCount !== other._usePointCount) {
			updates.push(E_Talent.USE_POINT_COUNT, this._usePointCount);
		}

		//天赋等级
		{
			const idx = E_Talent.TALENT_LEVEL;
			const ks1 = this._talentLevel.getKeys();
			const ks2 = other._talentLevel.getKeys();
			const vs1 = this._talentLevel.getValues();
			const vs2 = other._talentLevel.getValues();
			const rs = MathUtils.intersectSortedArray(ks1, ks2, vs1, vs2);
			if (rs[0].length > 0) {
				const list = rs[0];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getTalentLevel(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[1].length > 0) {
				const list = rs[1];
				for (let i = 0, len = list.length; i < len; i++) {
					const k = list[i];
					const newv = this.getTalentLevel(k);
					updates.push(idx, k, newv);
				}
			}
			if (rs[2].length > 0) {
				const list = rs[2];
				for (let i = 0, len = list.length; i < len; i++) {
					updates.push(idx, list[i], 0);
				}
			}
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(Talent.TOTAL_EVENT_ID, this.getV(0));
	}

}
